package com.kedou.sdk.ui.activity;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.kedou.sdk.assist.AlipayPayOperation;
import com.kedou.sdk.assist.CallbackObservable;
import com.kedou.sdk.assist.Constant;
import com.kedou.sdk.core.HttpEngineApi;
import com.kedou.sdk.handler.SimpleAsyncResponseHandler;
import com.kedou.sdk.params.CreateOrderResponseParams;
import com.kedou.sdk.params.PayChannelResponseParams;
import com.kedou.sdk.params.ResponseParams;
import com.kedou.sdk.params.bean.Goods;
import com.kedou.sdk.params.bean.PayChannel;
import com.kedou.sdk.params.bean.PayChannelInfo;
import com.kedou.sdk.params.bean.State;
import com.kedou.sdk.params.bean.VoucherModel;
import com.kedou.sdk.ui.assist.PayChannelListAdapter;
import com.kedou.sdk.ui.view.ListViewForScrollView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * Created by Administrator on 2017/6/8 0008.
 */

public class PaymentActivity extends AppBaseActivity implements AdapterView.OnItemClickListener, View.OnClickListener {

//    private static final String TAG = PaymentActivity.class.getSimpleName();
    private static final int REQUEST_CODE = 0x0000;
    private static final int APPLET_REQUEST_CODE = 0x0001;
    private static final int START_DEFAULT_BROWSER_REQUEST_CODE = 0x0003;
    private static final String UNION_PAY_MODE = "00";
    private static final String UNION_PAY_RESULT = "pay_result";

    private final CopyOnWriteArrayList<PayChannel> mDefaultShowChannels = new CopyOnWriteArrayList<>();
    private final CopyOnWriteArrayList<PayChannel> mDefaultHideChannels = new CopyOnWriteArrayList<>();

    private TextView mGoodsPriceTv;
    private TextView mGoodsDiscountPriceTv,mGoodsDiscountNumberTv,mFinalMoney,mYouhuiMoney,mVoucherTv;
    private Button mGoodsSubmitBtn;
    private ListViewForScrollView mPaymentChannelsLv;
    private View mShowMorePayChannelView;

    private Goods mGoods;
    private int mGetPayChannelTaskId;
    private int mCreateOrderTaskId;
    private PayChannelListAdapter mAdapter;
    private View lastSelectedView;
    private int lastSelectedPosition;

    private float mPriceRatio = 1f;
    private String mRatioText;

    private boolean isFirst =true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onInitViews();
    }

    @Override
    protected void onResume() {
        super.onResume();
        onInitData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        HttpEngineApi.getInstance().cancel(mCreateOrderTaskId);
    }

    private void onInitViews() {
        setContentView(getLayoutIdentifier("hnssn_activity_payment"));
        mGoodsPriceTv = findViewById(getViewIdentifier("hnssn_activity_payment_goods_price"));
        mGoodsDiscountPriceTv = findViewById(getViewIdentifier("hnssn_activity_payment_goods_discount_price"));
        mGoodsDiscountNumberTv = findViewById(getViewIdentifier("hnssn_activity_payment_goods_discount_number"));
        mVoucherTv = findViewById(getViewIdentifier("hnssn_activity_payment_youhui_price"));
        mVoucherTv.setOnClickListener(this);
        mFinalMoney = findViewById(getViewIdentifier("pay_finnal_money"));
        mYouhuiMoney = findViewById(getViewIdentifier("pay_finnal_youhui"));
        mGoodsSubmitBtn = findViewById(getViewIdentifier("hnssn_activity_payment_submit"));
        mPaymentChannelsLv = findViewById(getViewIdentifier("hnssn_activity_payment_type_lv"));
        mShowMorePayChannelView = findViewById(getViewIdentifier("hnssn_activity_payment_more"));
        mPaymentChannelsLv.setOnItemClickListener(this);
        mGoodsSubmitBtn.setOnClickListener(this);
    }

    private void onInitData() {
        Intent intent = getIntent();
        if (intent != null) {
            mGoods = intent.getParcelableExtra("goods");
            if (mGoods != null) {
                getPayChannel(mGoods);
            }
        }
    }

    private void generateDefaultDisplayChannels(List<PayChannel> source, List<PayChannel> show, List<PayChannel> hide) {
        show.clear();
        hide.clear();
        if (source != null & !source.isEmpty()) {
            for (PayChannel channel : source) {
                if (channel != null) {
                    if (channel.isHidden()) {
                        hide.add(channel);
                    } else {
                        show.add(channel);
                    }
                }
            }
        }
    }

    @Override
    public void onBackPressed() {
        if (!isForbidBackSuper()) {
            CallbackObservable observable = CallbackObservable.getInstance();
            String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
            super.onBackPressed();
        }
    }

    public void finishPaymentActivity(View view) {
        CallbackObservable observable = CallbackObservable.getInstance();
        String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
        observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
        finish();
    }

    public void showMorePayChannel(View view) {
        List<PayChannel> channels = (List<PayChannel>) mDefaultShowChannels.clone();
        channels.addAll(mDefaultHideChannels);
        mAdapter.setAdapterData(channels);
        mAdapter.notifyDataSetChanged();
        mShowMorePayChannelView.setVisibility(View.GONE);
    }


    private void getPayChannel(Goods goods) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(PayChannelResponseParams.class);
        mGetPayChannelTaskId = HttpEngineApi.getInstance().getPayChannelInfo(goods, handler);
    }

    private void createOrder(String payid,String vercherid, Goods goods) {
        SimpleAsyncResponseHandler handler = requestCallbackHandler(CreateOrderResponseParams.class);
        mCreateOrderTaskId = HttpEngineApi.getInstance().createOrder(payid,vercherid, goods, handler);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
            CallbackObservable observable = CallbackObservable.getInstance();
            String message = getString(getStringIdentifier("hnssn_h5payhint_success"));
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, message, null);
        } else if (START_DEFAULT_BROWSER_REQUEST_CODE == requestCode) {
            CallbackObservable observable = CallbackObservable.getInstance();
            String message = getString(getStringIdentifier("hnssn_h5payhint_unknown"));
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_UNKNOWN, message, null);
        } else if (APPLET_REQUEST_CODE == requestCode) {
            if (RESULT_CANCELED == resultCode) {
                CallbackObservable observable = CallbackObservable.getInstance();
                String message = getString(getStringIdentifier("hnssn_h5payhint_unknown"));
                observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_UNKNOWN, message, null);
            }
        }else if (4444 == requestCode){
            if(RESULT_OK == resultCode){
//                voucherModelIndex = ;
                initOrderPriceInfo(data.getIntExtra("index",-1));
            }
            return;
        }
//        else if (HeepayPayOperation.RESULT_CODE == resultCode) {
//            HeepayPayOperation.onActivityResult(requestCode, resultCode, data);
//        }
        else {
            //云闪付支付回调通知检测
            if (data != null && data.hasExtra(UNION_PAY_RESULT)) {
                String unionPayResult = data.getStringExtra(UNION_PAY_RESULT);
                if ("success".equalsIgnoreCase(unionPayResult)) {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    String message = getString(getStringIdentifier("hnssn_h5payhint_success"));
                    observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, message, null);
                } else if ("cancel".equalsIgnoreCase(unionPayResult)) {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
                    observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
                } else {
                    CallbackObservable observable = CallbackObservable.getInstance();
                    String message = getString(getStringIdentifier("hnssn_h5payhint_faile"));
                    observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_FAILED, message, null);
                }
            } else {
                CallbackObservable observable = CallbackObservable.getInstance();
                String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
                observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
            }
        }
        finish();
    }

    @Override
    public void onAsyncRequestResult(int flag, ResponseParams response, Object... params) {
        super.onAsyncRequestResult(flag, response, params);
        if (flag == mCreateOrderTaskId) {
            executeCreateOrderResult(response);
        } else if (flag == mGetPayChannelTaskId) {
            executePayChannelResult(response);
        }
    }
    private int voucherModelIndex= -1;

    private BigDecimal discountPrice,goodsPrice,voucherPrice;
    private String currencySymbol;
    private void initOrderPriceInfo(int index){
        Log.e("index",index+"....");
        voucherModelIndex = index;
        if(voucherModelIndex==-1){
            voucherPrice = new BigDecimal(0);
            mVoucherTv.setText(voucherModelList!=null&&voucherModelList.size()>0?"请选择":"暂无可用");
        }else{
            voucherPrice = new BigDecimal(voucherModelList.get(voucherModelIndex).getFaceValue());
            mVoucherTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"),currencySymbol, voucherPrice.floatValue()));
        }
        discountPrice = goodsPrice.subtract(voucherPrice).multiply(new BigDecimal(mPriceRatio));
        if (mPriceRatio != 1f) {
            mGoodsDiscountNumberTv.setText(mRatioText);
//            int resId = getStringIdentifier("hnssn_h5payhint_goods_discount_price");
//            mGoodsDiscountNumberTv.setText(getString(resId, (mPriceRatio * 10f)));
//                mGoodsDiscountPriceTv.setText("-¥"+(goodsPrice.subtract(discountPrice)));
            mGoodsDiscountPriceTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"), currencySymbol, goodsPrice.subtract(voucherPrice).subtract(discountPrice).floatValue()));
        } else {
            ((LinearLayout)mGoodsDiscountPriceTv.getParent()).setVisibility(View.GONE);

        }

        mFinalMoney.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, discountPrice.floatValue()));
        mYouhuiMoney.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, goodsPrice.subtract(discountPrice).floatValue()));
    }
    private void initOrderPriceInfo(PayChannel channel) {
        currencySymbol = channel.getCurrency();
        if (channel != null) {
            if(voucherModelIndex==-1){
                voucherPrice = new BigDecimal(0);
                mVoucherTv.setText(voucherModelList!=null&&voucherModelList.size()>0?"请选择":"暂无可用");
            }else{
                voucherPrice = new BigDecimal(voucherModelList.get(voucherModelIndex).getFaceValue());
                mVoucherTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"),currencySymbol, voucherPrice.floatValue()));
            }
            goodsPrice = channel.getCurrencyPrice();
            if (mPriceRatio != 1f) {
                discountPrice = goodsPrice.subtract(voucherPrice).multiply(new BigDecimal(mPriceRatio));
                mGoodsDiscountNumberTv.setText(mRatioText);
//                int resId = getStringIdentifier("hnssn_h5payhint_goods_discount_price");
//                mGoodsDiscountNumberTv.setText(getString(resId, (mPriceRatio * 10f)));
//                mGoodsDiscountPriceTv.setText("-¥"+(goodsPrice.subtract(discountPrice)));
                mGoodsDiscountPriceTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"), currencySymbol, goodsPrice.subtract(voucherPrice).subtract(discountPrice).floatValue()));
            } else {
                ((LinearLayout)mGoodsDiscountPriceTv.getParent()).setVisibility(View.GONE);
                discountPrice = goodsPrice.subtract(voucherPrice);
            }


            mGoodsPriceTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, goodsPrice.floatValue()));
            mFinalMoney.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, discountPrice.floatValue()));
            mYouhuiMoney.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, goodsPrice.subtract(discountPrice).floatValue()));
//            mGoodsSubmitBtn.setText(getString(getStringIdentifier("hnssn_pay_table_submit_text"), currencySymbol, discountPrice.floatValue()));
        }
//        if (channel != null) {
//            currencySymbol = channel.getCurrency();
//           goodsPrice = channel.getCurrencyPrice();
//            if (ratio != 1f) {
//                discountPrice = goodsPrice.multiply(new BigDecimal(ratio));
//                int resId = getStringIdentifier("hnssn_h5payhint_goods_discount_price");
//                mGoodsDiscountNumberTv.setText(getString(resId, (ratio * 10f)));
////                mGoodsDiscountPriceTv.setText("-¥"+(goodsPrice.subtract(discountPrice)));
//                mGoodsDiscountPriceTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"), currencySymbol, goodsPrice.subtract(discountPrice).floatValue()));
//            } else {
//                ((LinearLayout)mGoodsDiscountPriceTv.getParent()).setVisibility(View.GONE);
//                discountPrice = goodsPrice;
//            }
//            if(voucherModelIndex==-1){
//                voucherPrice = new BigDecimal(0);
//                mVoucherTv.setText("未使用");
//            }else{
//                voucherPrice = new BigDecimal(voucherModelList.get(voucherModelIndex).getFaceValue());
//                mVoucherTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"),currencySymbol, voucherPrice.floatValue()));
//            }
//
//            mGoodsPriceTv.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, goodsPrice.floatValue()));
//            mFinalMoney.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price"), currencySymbol, discountPrice.subtract(voucherPrice).floatValue()));
//            mYouhuiMoney.setText(getString(getStringIdentifier("hnssn_h5payhint_goods_price_sub"), currencySymbol, goodsPrice.subtract(discountPrice).add(voucherPrice).floatValue()));
////            mGoodsSubmitBtn.setText(getString(getStringIdentifier("hnssn_pay_table_submit_text"), currencySymbol, discountPrice.floatValue()));
//        }
    }
    private ArrayList<VoucherModel> voucherModelList;
    private void executePayChannelResult(ResponseParams response) {
        if (response instanceof PayChannelResponseParams) {
            PayChannelResponseParams responseParams = (PayChannelResponseParams) response;
            if (responseParams.isSuccess()) {


                PayChannelInfo payChannelInfo = responseParams.getData();

//                VoucherModel tmModel= new VoucherModel();
//                tmModel.setContent("fdfd");
//                tmModel.setGameName("df");
//                tmModel.setThreshold(0);
//                tmModel.setStatus(0);
//                tmModel.setFaceValue(1);
////
//                voucherModelList = new ArrayList<>();
//                voucherModelList.add(tmModel);
//                tmModel.setFaceValue(2);
//                voucherModelList.add(tmModel);
                voucherModelList = payChannelInfo.getVoucherList();
                if(isFirst){
                    isFirst = false;
                    if(voucherModelList!=null&&voucherModelList.size()>0){
                        voucherModelIndex=0;
                    }
                }
                if (payChannelInfo != null) {
                    mPriceRatio = payChannelInfo.getDiscount();
                    mRatioText = payChannelInfo.getDiscountText();
//                    mPriceRatio = payChannelInfo.getDiscount();
                    List<PayChannel> channels = payChannelInfo.getPayChannel();
                    if (!channels.isEmpty()) {
                        initOrderPriceInfo(channels.get(0));
                    }

                    generateDefaultDisplayChannels(channels, mDefaultShowChannels, mDefaultHideChannels);
                    if(mAdapter==null){
                        mAdapter = new PayChannelListAdapter(mGoods,payChannelInfo.getPtbMoney());
                        mPaymentChannelsLv.setAdapter(mAdapter);
                        mAdapter.setAdapterData(mDefaultShowChannels);
                        if (mDefaultHideChannels.isEmpty()) {
                            mShowMorePayChannelView.setVisibility(View.GONE);
                        } else {
                            mShowMorePayChannelView.setVisibility(View.VISIBLE);
                        }
                    }else {
                        if(mShowMorePayChannelView.getVisibility() ==View.VISIBLE){
                            mAdapter.setAdapterData(mDefaultShowChannels);
                            mAdapter.notifyDataSetChanged();
                        }else{
                            showMorePayChannel(null);
                        }

                    }


                } else {
                    finishPaymentActivity(null);
                }
            } else {
                finishPaymentActivity(null);
            }
        }

    }

    private void executeCreateOrderResult(ResponseParams response) {
        if (response instanceof CreateOrderResponseParams) {
            CreateOrderResponseParams responseParams = (CreateOrderResponseParams) response;
            HttpEngineApi.getInstance().getEngineConduits().saveCurrentOrder(responseParams.getData().getOrder_no());
            if(1==responseParams.getData().getPayment_success()){
                CallbackObservable observable = CallbackObservable.getInstance();
                String message = getString(getStringIdentifier("hnssn_h5payhint_success"));
                observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_SUCCESS, message, null);
                finish();
            }else {
                if (State.SUCCESS == responseParams.getCode()) {

                    switch (responseParams.getData().getOpen_with()) {
                        case 2:
                            weixinPay(responseParams.getData());
                            break;

                        case 3:
                            alipayPayV1(responseParams.getData());
                            break;
                        default:
                            startDefaultWebBrowser(responseParams.getData());
                            break;
                    }
            }

            }
        }
    }

    private void doStartUnionPayPlugin(CreateOrderResponseParams.CreateOrderResponseData response) {
//        if (response != null) {
//            UPPayAssistEx.startPay(this, null, null, response.getPay_info(), UNION_PAY_MODE);
//        }
    }




    private void weixinPay(CreateOrderResponseParams.CreateOrderResponseData response) {
        if (response != null) {

            webH5Pay(response);

        }
    }
    private void weixinAppPay(CreateOrderResponseParams.CreateOrderResponseData response) {
//        if (response != null) {
//            WeChatOperation.getInstance().startWeChatApplet(PaymentActivity.this,response.getPay_info());
//        }
    }

    private void weixinAppletPay(CreateOrderResponseParams.CreateOrderResponseData response) {
        if (response != null) {
            Intent intent = new Intent(Constant.LocalIntentAction.INTENT_AACTION_WECHAT_APPLET_PAY);
            intent.setPackage(getPackageName());
            intent.putExtra("wechat_applet_pay_info", response.getPay_info());
            startActivityForResult(intent, APPLET_REQUEST_CODE);
        }
    }

    private void alipayPayV1(final CreateOrderResponseParams.CreateOrderResponseData response) {
        Log.d("alipay","alipayPayV1");
        if (response != null) {
            new AlipayPayOperation(this).execute(response.getPay_info());
        }
    }

    private void webH5Pay(final CreateOrderResponseParams.CreateOrderResponseData response) {
        Intent intent = new Intent(this, WXH5PayActivity.class);
        intent.setPackage(getPackageName());
        intent.putExtra("weixinPay", response);
        startActivityForResult(intent, REQUEST_CODE);
    }

    private void startDefaultWebBrowser(final CreateOrderResponseParams.CreateOrderResponseData response) {
        String url = response != null ? response.getPay_info() : "";
        if (!TextUtils.isEmpty(url)) {
            try {
                startActivityForResult(new Intent(Intent.ACTION_VIEW, Uri.parse(url)), START_DEFAULT_BROWSER_REQUEST_CODE);
            } catch (ActivityNotFoundException exception) {
                final int resId = getStringIdentifier("hnssn_h5payhint_webclient_excepition");
                Toast.makeText(getApplicationContext(), resId, Toast.LENGTH_SHORT).show();

                CallbackObservable observable = CallbackObservable.getInstance();
                String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
                observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
            }
        } else {
            CallbackObservable observable = CallbackObservable.getInstance();
            String message = getString(getStringIdentifier("hnssn_h5payhint_cancel"));
            observable.callResponseResult(Constant.CallType.CALL_PAY, Constant.PayState.PAY_CANCEL, message, null);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (lastSelectedView == null) {
            View firstView = parent.getChildAt(parent.getFirstVisiblePosition());
            resetItemViewSelectedState(firstView, false);
        }

        if (lastSelectedView != view) {
            resetItemViewSelectedState(lastSelectedView, false);
            resetItemViewSelectedState(view, true);
            this.lastSelectedView = view;
            this.lastSelectedPosition = position;
            mAdapter.setLastSelectedIndex(position);
        }

        initOrderPriceInfo(mAdapter.getItem(position));
    }

    private void resetItemViewSelectedState(View view, boolean selected) {
        if (view != null) {
            Object obj = view.getTag();
            if (obj instanceof PayChannelListAdapter.ViewHolder) {
                PayChannelListAdapter.ViewHolder viewHolder = (PayChannelListAdapter.ViewHolder) obj;
                viewHolder.checked.setChecked(selected);
            }
        }
    }

    @Override
    public void onClick(View view) {
        if(view==mVoucherTv){
            Intent in = new Intent(PaymentActivity.this,VoucherChooseActivity.class);
            in.putParcelableArrayListExtra("models",voucherModelList);
            in.putExtra("price",goodsPrice.floatValue());
            in.putExtra("index",voucherModelIndex);
            startActivityForResult(in,4444);
        }else if(view==mGoodsSubmitBtn){
            PayChannel channel = mAdapter.getItem(lastSelectedPosition);
            createOrder(String.valueOf(channel.getPay_id()),voucherModelIndex==-1?"0":voucherModelList.get(voucherModelIndex).getId(), mGoods);
        }
//        startActivity(new Intent(PaymentActivity.this,PlatFormCoinActivity.class));
//        PayType type = channel.getPayTypeEnum();
//        switch (type) {
//            case WEIXIN_PAY:
//            case WEIXIN_APPLET_PAY:
//                payByWeixin(type);
//                break;
//            case UNION_APP_PAY:
//                payByUnionAppPay(type);
//                break;
//            default:
//        }

    }
}
